package common

import (
	"gitee.com/sansaniot/ssiot-gw-lib-comm/comm/types"
	model2 "gitee.com/sansaniot/ssiot-gw-lib-comm/model"
	"github.com/rs/zerolog/log"
)

var (
	OnConnect                  types.OnConnectFunc
	OnDisconnect               types.OnDisconnectFunc
	CreateTaskAfterConnect     types.CreateTaskAfterConnectFunc
	DestroyTaskAfterDisconnect types.DestroyTaskAfterDisconnectFunc
	OnReceiveData              types.ReceiveDataFunc
)

// StartModbusProbe 创建dpu采集任务
func StartModbusProbe(commId string) {
	// 如果已存在dpu任务则不创建
	if _, ok := types.DpuTask.Load(commId); ok {
		return
	}

	configModel := model2.DpuConfig{CommId: commId}
	config := configModel.GetByCommId()
	// 无配置
	if config == nil {
		return
	}

	// 创建采集任务
	if CreateTaskAfterConnect != nil {
		if CreateTaskAfterConnect(commId, string(config)) != nil {
			types.DpuTask.Store(commId, true)
		}
	}
}

// EndModbusProbe 终止dpu采集对象
func EndModbusProbe(commId string) {
	_, ok := types.DpuTask.Load(commId)
	if !ok {
		log.Info().Msgf("no dpu task for commId %s", commId)
		return
	}

	if DestroyTaskAfterDisconnect != nil {
		if DestroyTaskAfterDisconnect(commId) != nil {
			types.DpuTask.Delete(commId)
		}
	}
}

func InitCommandChannel(commId string) {
	//初始化接收采集命令的通道
	_, ok1 := types.ProbeCommandChannels.Load(commId)
	if !ok1 {
		types.ProbeCommandChannels.Store(commId, make(chan *types.ProbeCommand, 5))
	}
}

func InitDataChannel(commId string) {
	//初始化接收采集数据的通道
	_, ok := types.ProbeDataChannels.Load(commId)
	if !ok {
		types.ProbeDataChannels.Store(commId, make(chan map[string]interface{}, 5))
	}
}

func HasInitDataChannel(commId string) bool {
	_, ok := types.ProbeDataChannels.Load(commId)
	return ok
}

func HasInitCmdChannel(commId string) bool {
	_, ok := types.ProbeCommandChannels.Load(commId)
	return ok
}

func Online(commId string) {
	dev := &model2.Device{}
	dev.CommId = commId
	devs, _ := dev.FindByCommId()

	for _, d := range devs {
		if OnConnect != nil {
			OnConnect(d.DevSn)
		}
	}
}

func Offline(commId string) {
	dev := &model2.Device{}
	dev.CommId = commId
	devs, _ := dev.FindByCommId()

	for _, d := range devs {
		if OnDisconnect != nil {
			OnDisconnect(d.DevSn)
		}
	}
}
